package com.fingard.dsp.bank.directbank.bocom01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IRealTime;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingle;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import sun.misc.BASE64Encoder;

public class BOCOM01RealTime extends BOCOM01Base implements IRealTime {
    @Override
    public RetAtsSingle d_9108_RealTimeRec(ReqSingle p_req9108) throws Exception {
        //返回ATS的对象
        if ("1".equals(p_req9108.singleDetail.isPrivate)) {
            return d_9108_RealTimeRec_pub(p_req9108);
        } else {
            return d_9108_RealTimeRec_pub(p_req9108);
        }

    }

    public RetAtsSingle d_9108_RealTimeRec_private(ReqSingle p_req9108) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req9108.reqHeader);
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
        try {
            tr_code = "FHTS01";
            String transCode = "100301";
            req_no = p_req9108.singleDetail.askNumber;
            XmlTextWriter xmlWriter = new XmlTextWriter();// 发银行报文的XML对象
            // 写入通用的头部节点
            writeCommonHeader(xmlWriter);
            String contractNo = getBankConfig().getMapValueByKey("cagrNo" + transCode, p_req9108.singleDetail.recAct);//有问题
            XElement tmpXElement = new XElement("body", "");
            XElement dataXElement = new XElement("data", "");
            XmlTextWriter dataWriter = new XmlTextWriter();
            dataXElement.addChild(new XElement("transCode", transCode));//交易码
            dataXElement.addChild(new XElement("subdate", Format.Date8Format.format(Format.Date10Format.parse(p_req9108.singleDetail.payDate))));//委托日期
            dataXElement.addChild(new XElement("outid", p_req9108.singleDetail.askNumber));//交易序号
            dataXElement.addChild(new XElement("sndOrgNo", ""));//收费机构代码
            dataXElement.addChild(new XElement("sndBranchNo", ""));//机构分支代码
            dataXElement.addChild(new XElement("contractno", contractNo));//合同号
            dataXElement.addChild(new XElement("custno", getValueAsString("custno")));//用户编号
            dataXElement.addChild(new XElement("busKnd", getBankConfig().getMapValueByKey("PayType", p_req9108.singleDetail.payType)));//业务种类
            dataXElement.addChild(new XElement("bankno", p_req9108.singleDetail.cnapsCode));//付款行行号
            dataXElement.addChild(new XElement("rcvBkn", p_req9108.singleDetail.cnapsCode));//付款清算行行号
            dataXElement.addChild(new XElement("acctno", p_req9108.singleDetail.payAct));//付款人账号
            dataXElement.addChild(new XElement("acctname", p_req9108.singleDetail.payName));//付款人名称
            dataXElement.addChild(new XElement("currency", convertCurToBank(p_req9108.singleDetail.payCur)));//付款人币种
            dataXElement.addChild(new XElement("paymoney", p_req9108.singleDetail.payAmount));//金额
            dataXElement.addChild(new XElement("hfe", ""));//手续费
            dataXElement.addChild(new XElement("desc", p_req9108.singleDetail.useType));//附言
            dataXElement.addChild(new XElement("remark", p_req9108.singleDetail.purpose));//备注
            nodeAnalysis(p_req9108.singleDetail.srcXElement, dataXElement, "GBK");
            dataWriter.writeXElement(dataXElement);
            String dataxml = dataWriter.toXmlString();
            dataxml = dataxml.substring("<data>".length(), dataxml.length() - "</data>".length());
            WriteBankLogLn("base64编码前的报文内容：" + dataxml);
            tmpXElement.addChild(new XElement("data", new String(new BASE64Encoder().encode(dataxml.getBytes(getCharset())))));
            xmlWriter.writeXElement(tmpXElement);
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());// 发送银行
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                // 解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String ans_code = tmpBkReader.getFirstText("/ap/head/ans_code");
                    if ("0".equals(ans_code)) {
                        tmpRetDetail.respCode = "0";
                        tmpRetDetail.respInfo = tmpBkReader.getFirstText("/ap/head/ans_info");
                        String responseCode = tmpBkReader.getFirstText("/ap/body/responseCode");
                        tmpRetDetail.reqSeqID = tmpBkReader.getFirstText("/ap/body/outid");
                        tmpRetDetail.transState = responseCode;
                        tmpRetDetail.payInfoCode = responseCode;
                        tmpRetDetail.outTransID = tmpBkReader.getFirstText("/ap/body/transno");
                    } else {
                        tmpRetDetail.respCode = "-1";
                        tmpRetDetail.respInfo = tmpBkReader.getFirstText("/ap/head/ans_info");
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpStrRet[1];
            }

        } catch (Exception e) {
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = e.toString();
            e.printStackTrace();
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    public RetAtsSingle d_9108_RealTimeRec_pub(ReqSingle p_req9108) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req9108.reqHeader);
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
        try {
            tr_code = "210401";
            req_no = p_req9108.singleDetail.askNumber;
            XmlTextWriter xmlWriter = new XmlTextWriter();// 发银行报文的XML对象
            // 写入通用的头部节点
            writeCommonHeader(xmlWriter);
            XElement tmpXElement = new XElement("body", "");
            tmpXElement.addChild(new XElement("dealNo", p_req9108.singleDetail.askNumber));
            String contractNo = getBankConfig().getMapValueByKey("cagrNo" + tr_code, p_req9108.singleDetail.recAct);
            tmpXElement.addChild(new XElement("cagrNo", contractNo));
            tmpXElement.addChild(new XElement("recAccNo", p_req9108.singleDetail.recAct));
            tmpXElement.addChild(new XElement("recAccName", p_req9108.singleDetail.recName));
            tmpXElement.addChild(new XElement("totalNum", "1"));
            tmpXElement.addChild(new XElement("batchSum", "1"));
            tmpXElement.addChild(new XElement("offset", "0"));
            tmpXElement.addChild(new XElement("totalAmt", p_req9108.singleDetail.payAmount));
            tmpXElement.addChild(new XElement("batchSumAmt", p_req9108.singleDetail.payAmount));
            tmpXElement.addChild(new XElement("subAgrNo", p_req9108.singleDetail.authCode));
            tmpXElement.addChild(new XElement("payAccNo", p_req9108.singleDetail.payAct));
            tmpXElement.addChild(new XElement("payAccName", p_req9108.singleDetail.payName));
            tmpXElement.addChild(new XElement("feeName", p_req9108.singleDetail.reqReserved2));
            tmpXElement.addChild(new XElement("chgmod", "0"));
            tmpXElement.addChild(new XElement("usrdefineValue", ""));
            tmpXElement.addChild(new XElement("tranAmt", p_req9108.singleDetail.payAmount));
            tmpXElement.addChild(new XElement("rem", p_req9108.singleDetail.purpose));
            nodeAnalysis(p_req9108.singleDetail.srcXElement, tmpXElement, "GBK");
            xmlWriter.writeXElement(tmpXElement);
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());// 发送银行
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                // 解析银行返回
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    tmpRetDetail.respCode = "0";

                    if (!tmpBkReader.getFirstText("/ap/head/particular_code").equals("")) {
                        tmpRetDetail.reqSeqID = tmpBkReader.getFirstText("/ap/head/req_no");
                        tmpRetDetail.transState = tmpBkReader.getFirstText("/ap/head/particular_code");
                        tmpRetDetail.payInfoCode = tmpBkReader.getFirstText("/ap/head/particular_code");
                        tmpRetDetail.respInfo = tmpBkReader.getFirstText("/ap/head/particular_info");
                        String ans_info = tmpBkReader.getFirstText("/ap/head/ans_info");
                        if (StringHelper.hasAnyChar(ans_info)) {
                            tmpRetDetail.respInfo = ans_info + "+" + tmpRetDetail.respInfo;
                            if ("9003".equals(tmpRetDetail.transState)) {
                                tmpRetDetail.transState = tmpRetDetail.transState + "+" + ans_info;
                                tmpRetDetail.payInfoCode = tmpRetDetail.transState;
                            }
                        }
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpStrRet[1].toString();
            }

        } catch (Exception e) {
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = e.toString();
            e.printStackTrace();
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }


    @Override
    public RetAtsSingle d_9144_QryRealTimeRec(ReqQrySingle p_req9144) throws Exception {
        //返回ATS的对象
        if ("1".equals(p_req9144.isPrivate)) {
            return d_9144_QryRealTimeRec_pub(p_req9144);
        } else {
            return d_9144_QryRealTimeRec_pub(p_req9144);
        }

    }

    public RetAtsSingle d_9144_QryRealTimeRec_private(ReqQrySingle p_req9144) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req9144.reqHeader);
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
        try {
            tr_code = "FHTS01";
            String transCode = "200102";
            XmlTextWriter xmlWriter = new XmlTextWriter();// 发银行报文的XML对象
            writeCommonHeader(xmlWriter);// 写入通用的头部节点
            xmlWriter.writeStartElement("body");
            XElement dataXElement = new XElement("data", "");
            XmlTextWriter dataWriter = new XmlTextWriter();
            dataXElement.addChild(new XElement("transCode", transCode));//交易码
            dataXElement.addChild(new XElement("sndOrgNo", bankFront.org));//收费机构代码
            dataXElement.addChild(new XElement("sndBranchNo", ""));//机构分支代码
            dataXElement.addChild(new XElement("thdSeqNo", p_req9144.askNumber));//交易序号
            dataWriter.writeXElement(dataXElement);
            String dataxml = dataWriter.toXmlString();
            dataxml = dataxml.substring("<data>".length(), dataxml.length() - "</data>".length());
            WriteBankLogLn("base64编码前的报文内容：" + dataxml);
            xmlWriter.writeXElement(new XElement("data", new String(new BASE64Encoder().encode(dataxml.getBytes(getCharset())))));
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            XmlTextReader tmpBkReader;
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String ans_code = tmpBkReader.getFirstText("/ap/head/ans_code");
                    String responseCode = tmpBkReader.getFirstText("/ap/body/responseCode");
                    if ("0".equals(ans_code) && "000000".equals(responseCode)) {
                        tmpRetDetail.respCode = "0";
                        tmpRetDetail.respInfo = tmpBkReader.getFirstText("/ap/body/responseMessage");//
                        tmpRetDetail.reqSeqID = tmpBkReader.getFirstText("/ap/body/outid");//
                        tmpRetDetail.transState = tmpBkReader.getFirstText("/ap/body/txnSts");//U-预计，S-成功，F-失败，C-冲正，T-超时
                        tmpRetDetail.payInfoCode = tmpRetDetail.transState;
                        tmpRetDetail.transAmt = tmpBkReader.getFirstText("/ap/body/paymoney");//

                    } else {
                        tmpRetDetail.respCode = "-1";
                        tmpRetDetail.respInfo = tmpBkReader.getFirstText("/ap/body/responseMessage");
                    }

                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }

            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }
        if ("-1".equals(tmpRetDetail.respCode) && StringHelper.isNullOrEmpty(p_req9144.askNumber)) {
            tmpRetDetail.reqSeqID = p_req9144.askNumber;
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    public RetAtsSingle d_9144_QryRealTimeRec_pub(ReqQrySingle p_req9144) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req9144.reqHeader);
        RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
        try {
            tr_code = "210402";
            XmlTextWriter xmlWriter = new XmlTextWriter();// 发银行报文的XML对象
            writeCommonHeader(xmlWriter);// 写入通用的头部节点
            xmlWriter.writeStartElement("body");
            xmlWriter.writeElementString("query_flag", "1");
            xmlWriter.writeElementString("flwno", p_req9144.askNumber);
            xmlWriter.writeElementString("pageSize", "");
            xmlWriter.writeElementString("beginPos", "");
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            XmlTextReader tmpBkReader;
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/head/particular_code");
                    String tmprspmsg = tmpBkReader.getFirstText("/ap/head/particular_info");
                    if (isActiveRetCode(tmpRetCode)) {
                        String serial_record = tmpBkReader.getFirstText("/ap/body/serialRecord");
                        int FieldNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/body/fieldNum"));
                        int RecordNum = Integer.parseInt(tmpBkReader.getFirstText("/ap/body/recordNum"));
                        java.util.List<String[]> listStrings = DealMFSText(serial_record, '|', FieldNum, RecordNum);
                        if (listStrings.size() > 0) {
                            listStrings.remove(0);
                            for (String[] strings : listStrings) {
                                //0.网银流水号|1.付款签约编号|2.付款账号|3.付款户名|4.缴费户名|5.收款方式|6.自定义字段值|7.应收金额|8.实收金额|9.备注|10.状态|11.错误信息|
                                tmpRetDetail.respCode = "0";
                                tmpRetDetail.respInfo = strings[11];
                                tmpRetDetail.transState = tmpRetCode + "+" + strings[10];
                                tmpRetDetail.payInfoCode = tmpRetDetail.transState;
                                tmpRetDetail.reqSeqID = p_req9144.askNumber;
                                tmpRetDetail.transAmt = strings[8];
                            }
                        } else {
                            tmpRetDetail.respCode = "-1";
                            tmpRetDetail.respInfo = tmprspmsg;
                        }
                    } else if ("0007".equals(tmpRetCode) && "数据库记录不存在".equals(tmprspmsg)) {
                        tmpRetDetail.respCode = "0";
                        tmpRetDetail.transState = "PaymentFailed";
                        tmpRetDetail.payInfoCode = "";
                        tmpRetDetail.respInfo = tmprspmsg;
                        tmpRetDetail.reqSeqID = p_req9144.askNumber;

                    } else if (getBankConfig().getValueAsString("canBeFailed").contains(p_req9144.askNumber)) {
                        tmpRetDetail.respCode = "0";
                        tmpRetDetail.transState = "PaymentFailed";
                        tmpRetDetail.payInfoCode = "";
                        tmpRetDetail.respInfo = tmprspmsg;
                        tmpRetDetail.reqSeqID = p_req9144.askNumber;
                    } else {
                        tmpRetDetail.respCode = "-1";
                        tmpRetDetail.respInfo = tmprspmsg;

                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }

            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }
        if ("-1".equals(tmpRetDetail.respCode) && StringHelper.isNullOrEmpty(p_req9144.askNumber)) {
            tmpRetDetail.reqSeqID = p_req9144.askNumber;
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }
}
